package myHeap;

import java.util.Arrays;

public class MyHeap {
    //模拟实现大根堆，本质是完全二叉树
    public final static int DEAFUILT_CAPICITY = 10;
    int[] heap = new int[DEAFUILT_CAPICITY];
    int usedSize = 0;

    //构造大根堆
    public void createBigHeap(int[] heap) {
        for (int i = (usedSize - 2) / 2; i >= 0; i--) { //后最后一个父节点往前开始向下调整
            shiftDown(i, usedSize);
        }
    }

    //向下调整
    private void shiftDown(int parent, int len) {
        int child = parent * 2 + 1;
        while (parent < len) {
            if (child + 1 < len && this.heap[child] < this.heap[child + 1]) {
                child++; //保证child的位置一定是两个孩子中更大的下标
            }
            if (this.heap[parent] < this.heap[child]) { //如果孩子结点比较大，那就交换
                int tmp = this.heap[parent];
                this.heap[parent] = this.heap[child];
                this.heap[child] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break; //如果双亲结点已经比较大了，那就说明下边的已经是大根堆了
            }
        }
    }

    //添加结点，在数组的最后增加一个节点，并开始向上调整
    public void offer(int val) {
        if (this.isFull()) {
            heap = Arrays.copyOf(heap, 2 * heap.length);
        }
        heap[usedSize++] = val;
        shiftUp(usedSize - 1);
    }

    //向上调整
    private void shiftUp(int child) { //孩子结点
        int parent = (child - 1) / 2; //双亲结点
        while (child > 0) {
            if (this.heap[child] > this.heap[parent]) {
                int tmp = this.heap[child];
                this.heap[child] = this.heap[parent];
                this.heap[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    //删除节点：让堆顶元素和最后一个有效元素交换位置，并且做一次向上调整
    public void poll() {
        if (this.isEmpty()) {
            throw new RuntimeException("堆为空，删除失败");
        }
        heap[0] = heap[--usedSize]; //直接将最后一个节点覆盖到第一个元素
        shiftDown(0, usedSize);
    }

    public int peek() {
        if (this.isEmpty()) {
            return -1;
        }
        return this.heap[0];
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public boolean isFull() {
        return usedSize == heap.length;
    }
}
